package com.circus.trace.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.nutz.dao.Cnd;
import org.nutz.img.Images;
import org.nutz.lang.Files;
import org.nutz.lang.Streams;
import org.nutz.lang.Times;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.nutz.qrcode.QRCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.circus.trace.bean.acl.User;
import com.circus.trace.biz.acl.UserService;

import club.zhcs.captcha.DefaultCaptchaGener;

@Controller
@RequestMapping("image")
public class ImageController {

	@Autowired
	UserService userService;

	final static String BASE_PATH = "~/upload/";

	@GetMapping("avatar")
	public void avatar(@RequestParam(value = "id", required = false, defaultValue = "0") long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = null;
		if (id == 0) {
			user = userService.fetch(Cnd.where("name", "=", SecurityUtils.getSubject().getPrincipal()));
		} else {
			user = userService.fetch(id);
		}
		Images.write(Images.createAvatar(user == null ? new DefaultCaptchaGener("NUTZONEKEY").gen(3) : user.getNickName()), "png", response.getOutputStream());
	}

	@PostMapping("kind/upload")
	@ResponseBody
	public NutMap kinduUpload(@RequestParam("imgFile") MultipartFile file, @RequestParam(value = "key", defaultValue = "") String key,
			@RequestParam(value = "base", defaultValue = "") String base) throws IOException {
		String path = Times.format("yyyy-MM-dd-HH-mm-ss-", Times.now()) + R.random(1, 1000);
		Streams.writeAndClose(Streams.fileOut(Files.createFileIfNoExists(BASE_PATH + path)), file.getInputStream());
		return NutMap.NEW().addv("error", 0).addv("url", base + "image/" + path).addv("key", key);
	}

	@GetMapping("/{path}")
	public void view(@PathVariable("path") String path, HttpServletResponse response) throws IOException {
		Images.write(Images.read(Files.checkFile(BASE_PATH + path)), "png", response.getOutputStream());
	}
	
	@GetMapping("/qr/{id}")
	public void qrcode(@PathVariable("id") long id, HttpServletResponse response) throws IOException {
		Images.write(QRCode.toQRCode(String.format("https://mxkf.kerbores.com/wap/index.html#/product/%d", id)), "png", response.getOutputStream());
	}
}